package top.malaoshi.webmvc.parameter;

import org.springframework.web.multipart.MultipartFile;
import top.malaoshi.webmvc.exception.RequestParamResolverException;
import top.malaoshi.webmvc.info.MethodsArgumentInfo;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.Collection;

public class MultipartArrayResolver extends AbstractResolver implements RequestParamAndMethodArgsResolver{

    @Override
    public Object resolver(HttpServletRequest request, HttpServletResponse response, MethodsArgumentInfo mai) throws RequestParamResolverException {
        checkNameAndValue(mai);
        MultipartFile[] ret = null;
        try {
            Collection<Part> parts = request.getParts();
            ret = new MultipartFile[parts.size()];
            parts.toArray(ret);
        } catch (IOException e) {
            throw new RequestParamResolverException(e);
        } catch (ServletException e) {
            throw new RequestParamResolverException(e);
        }
        checkRequired(ret,mai);
        return ret;

    }
}
